﻿using System;
using System.Text.RegularExpressions;
using System.Text;
using System.Globalization;

namespace CzfSDK
{
	public static class StringTool
	{
		/// <summary>
		/// 删除字符串尾
		/// </summary>
		/// <returns></returns>
		/// <param name="str">String.</param>
		/// <param name="end">End.</param>
		public static string CzfTrimEnd(this string str, string end)
		{
			var length = str.Length;
			if (length > end.Length) {
				var sub = str.Substring (length - end.Length, end.Length);
				if (sub == end)
					return str.Substring (0, length - end.Length);
			}
			return str;
		}

		public static string CzfFormat(this string str, params object[] args)
		{
			if (args != null && args.Length > 0) {
				for (int i = 0; i < args.Length; i++) {
					var s = args [i] == null ? "NULL" : args [i].ToString ();
					str = str.Replace ("{" + i + "}", s);
				}
			}

			return str;
		}

		public static string GetRandomStr(int len)
		{			
			var str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
			string ret = "";
			for (int i = 0; i < len; i++)
			{
				ret += str.Substring(RandomTool.Rand(0, str.Length - 1), 1);
			}
			return ret;
		}

		public static int ToInt(this string str)
		{
			return Convert.ToInt32 (str);
		}

		/// <summary>
		/// \uXXXX转中文
		/// </summary>
		/// <returns>The G b2312.</returns>
		/// <param name="str">String.</param>
		public static string ToGB2312(this string str)
		{
			var mc = Regex.Matches(str, @"\\u([\w]{2})([\w]{2})", (RegexOptions)(8 | 1));
			var bts = new byte[2];
			foreach(Match m in mc )
			{
				bts[0] = (byte)int.Parse(m.Groups[2].Value, NumberStyles.HexNumber);
				bts[1] = (byte)int.Parse(m.Groups[1].Value, NumberStyles.HexNumber);
				var s = Encoding.Unicode.GetString(bts);
				str = str.Replace (m.Value, s);
			}
			return str;
		}
	}
}

